//
//  NotifyViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/29.
//

#import "NotifyViewController.h"
#import "InviteView.h"

#import "UIImageView+WebCache.h"
#import <UserNotifications/UserNotifications.h>

@interface NotifyViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSMutableArray *batteryArray;
@property (nonatomic,strong) NSMutableArray *driveArray;
@property (nonatomic,strong) UIButton *notify;
@property (nonatomic,strong) UIView *notifyView;

@end

@implementation NotifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
            
    self.view.backgroundColor = WhiteColor;
    [self getNotifySetting];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReloadNotification) name:Noti_ReloadNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVHEIGHT)];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, 6, SCREEN_WIDTH-32, 32)];
    title.font = REAL_MEDIUM_FONT(24);
    title.text = @"智能通知";
    title.textColor = RealBlackColor;
    [_scrollView addSubview:title];
    
    _notify = [[UIButton alloc] initWithFrame:CGRectMake(16, title.maxY+16, _scrollView.width-32, 42)];
    _notify.backgroundColor = NormalMainColor;
    _notify.layer.masksToBounds = YES;
    [_notify.layer setCornerRadius:16];
    [_notify setImage:[UIImage imageNamed:@"notify_bling"] forState:UIControlStateNormal];
    [_notify setTitle:@" 点击打开通知权限，不错过任何家人消息" forState:UIControlStateNormal];
    [_notify.titleLabel setFont:DEFAULT_FONT(13)];
    [_notify setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    _notify.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_scrollView addSubview:_notify];
    _notify.hidden = YES;
    [[_notify rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
    }];
    
    _notifyView = [[UIView alloc] initWithFrame:CGRectMake(0, (_notify.hidden?48:112), SCREEN_WIDTH, 0)];
    [_scrollView addSubview:_notifyView];
    
    [self ReloadNotification];
    
    UILabel *battry = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, SCREEN_WIDTH-32, 16)];
    battry.font = REAL_MEDIUM_FONT(14);
    battry.textColor = GraryHeavyLightColor;
    battry.text = @"低电量通知";
    [_notifyView addSubview:battry];
    
    UILabel *battryLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, battry.maxY+2, SCREEN_WIDTH-32, 22)];
    battryLabel.font = DEFAULT_FONT(12);
    battryLabel.textColor = GraryTooHeavyColor;
    battryLabel.text = @"当电量低于10%时，会收到通知";
    [_notifyView addSubview:battryLabel];
    
    UIView *battryView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(battryLabel.frame)+8, SCREEN_WIDTH-32, self.batteryArray.count*66)];
    battryView.layer.masksToBounds = YES;
    [battryView.layer setCornerRadius:12];
    battryView.backgroundColor = RealWhiteColor;
    [_notifyView addSubview:battryView];
    
    for (int i=0; i<self.batteryArray.count; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, i*66, battryView.width, 66)];
        [battryView addSubview:view];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(16, 12, 42, 42)];
        [img.layer setCornerRadius:16];
        img.layer.masksToBounds = YES;
        img.backgroundColor = GraryLightColor;
        [img sd_setImageWithURL:[NSURL URLWithString:self.batteryArray[i][@"avatar"]]];
        [view addSubview:img];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(img.frame)+12, img.y, view.width-CGRectGetMaxX(img.frame)-100, img.height)];
        name.textColor = GraryHeavyLightColor;
        name.font = REAL_MEDIUM_FONT(15);
        name.text = self.batteryArray[i][@"nickName"];
        [view addSubview:name];
        
        UISwitch *battrySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(view.width-64, (view.height-26)/2, 48, 26)];
        [battrySwitch setFrame:CGRectMake(view.width-battrySwitch.width-16, (view.height-battrySwitch.height)/2, battrySwitch.width, battrySwitch.height)];
        battrySwitch.onTintColor = NormalMainColor;
        battrySwitch.tintColor = RealWhiteColor;
        [battrySwitch setOn:[self.batteryArray[i][@"status"] boolValue] animated:NO];
        battrySwitch.tag = 50+i;
        [battrySwitch addTarget:self action:@selector(switchBattryAction:) forControlEvents:UIControlEventValueChanged];
        [view addSubview:battrySwitch];
    }
    
    UILabel *safe = [[UILabel alloc] initWithFrame:CGRectMake(16, battryView.maxY+22, 88, 16)];
    safe.font = REAL_MEDIUM_FONT(14);
    safe.textColor = GraryHeavyLightColor;
    safe.text = @"安全驾驶通知";
    [_notifyView addSubview:safe];
    
    UILabel *safeLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, safe.maxY+2, SCREEN_WIDTH-32, 22)];
    safeLabel.font = DEFAULT_FONT(12);
    safeLabel.textColor = GraryTooHeavyColor;
    safeLabel.text = @"当驾车完成时，会收到通知";
    [_notifyView addSubview:safeLabel];
        
    UIView *safeView = [[UIView alloc] initWithFrame:CGRectMake(16, safeLabel.maxY+8, SCREEN_WIDTH-32, self.driveArray.count*66)];
    safeView.layer.masksToBounds = YES;
    [safeView.layer setCornerRadius:12];
    safeView.backgroundColor = RealWhiteColor;
    [_notifyView addSubview:safeView];
    
    for (int i=0; i<self.driveArray.count; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, i*66, safeView.width, 66)];
        [safeView addSubview:view];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(16, 12, 42, 42)];
        [img.layer setCornerRadius:16];
        img.layer.masksToBounds = YES;
        img.backgroundColor = GraryLightColor;
        [img sd_setImageWithURL:[NSURL URLWithString:self.driveArray[i][@"avatar"]]];
        [view addSubview:img];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(img.frame)+12, img.y, view.width-CGRectGetMaxX(img.frame)-100, img.height)];
        name.textColor = GraryHeavyLightColor;
        name.font = REAL_MEDIUM_FONT(15);
        name.text = self.driveArray[i][@"nickName"];
        [view addSubview:name];
        
        UISwitch *safeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(view.width-64, (view.height-26)/2, 48, 26)];
        [safeSwitch setFrame:CGRectMake(view.width-safeSwitch.width-16, (view.height-safeSwitch.height)/2, safeSwitch.width, safeSwitch.height)];
        safeSwitch.onTintColor = NormalMainColor;
        safeSwitch.tintColor = RealWhiteColor;
        [safeSwitch setOn:[self.driveArray[i][@"status"] boolValue] animated:NO];
        safeSwitch.tag = 100+i;
        [safeSwitch addTarget:self action:@selector(switchSafeAction:) forControlEvents:UIControlEventValueChanged];
        [view addSubview:safeSwitch];
    }
    
    UILabel *location = [[UILabel alloc] initWithFrame:CGRectMake(16, safeView.maxY+22, SCREEN_WIDTH-32, 16)];
    location.font = REAL_MEDIUM_FONT(14);
    location.textColor = GraryHeavyLightColor;
    location.text = @"位置通知";
    [_notifyView addSubview:location];
    
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, location.maxY+2, SCREEN_WIDTH-32, 22)];
    locationLabel.font = DEFAULT_FONT(12);
    locationLabel.textColor = GraryTooHeavyColor;
    locationLabel.text = @"当到达或离开某个位置，会收到通知";
    [_notifyView addSubview:locationLabel];
    
    UIButton *locationView = [[UIButton alloc] initWithFrame:CGRectMake(16, locationLabel.maxY+8, SCREEN_WIDTH-36, 60)];
    locationView.layer.masksToBounds = YES;
    [locationView.layer setCornerRadius:12];
    locationView.backgroundColor = RealWhiteColor;
    [locationView setImage:[UIImage imageNamed:@"location_notify"] forState:UIControlStateNormal];
    [locationView setTitle:@" 在首页“位置”中编辑位置通知" forState:UIControlStateNormal];
    [locationView setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
    locationView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [locationView.titleLabel setFont:REAL_MEDIUM_FONT(15)];
    [_notifyView addSubview:locationView];

    _notifyView.height = locationView.maxY;    
    
    [_scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(_notifyView.frame)+32)];
}

- (void)getNotifySetting
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/batterynotificationlist"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            self.batteryArray = [NSMutableArray array];
            if ([responseObject[@"data"] isKindOfClass:[NSArray class]] && [responseObject[@"data"] count]>0) {
                for (NSDictionary *dic in responseObject[@"data"]) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
                    [self.batteryArray addObject:dict];
                }
                {
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/system/group/safedrivenotificationlist"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            self.driveArray = [NSMutableArray array];
                            for (NSDictionary *dic in responseObject[@"data"]) {
                                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
                                [self.driveArray addObject:dict];
                            }
                            [self initView];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }
            }else {
                
                UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, NAVHEIGHT+6, SCREEN_WIDTH-32, 32)];
                title.font = REAL_MEDIUM_FONT(24);
                title.text = @"智能通知";
                title.textColor = RealBlackColor;
                [self.view addSubview:title];
                
                UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-180)/2, title.maxY+124, 180, 180)];
                img.image = [UIImage imageNamed:@"no_notify"];
                [self.view addSubview:img];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-180)/2, img.maxY+8, 180, 26)];
                label.textAlignment = NSTextAlignmentCenter;
                label.font = DEFAULT_FONT(16);
                label.text = @"需要一个成员加入家庭后\n才可以开启智能通知";
                label.numberOfLines = 0;
                [label sizeToFit];
                label.textColor = GraryTooHeavyColor;
                [label setFrame:CGRectMake((SCREEN_WIDTH-label.width)/2, img.maxY+8, label.width, label.height)];
                [self.view addSubview:label];
                
                UIButton *add = [[UIButton alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT-100, SCREEN_WIDTH-32, 60)];
                add.backgroundColor = NormalMainColor;
                add.layer.masksToBounds = YES;
                [add.layer setCornerRadius:20];
                [add setImage:[UIImage imageNamed:@"add_new_home"] forState:UIControlStateNormal];
                [add setTitle:@" 添加新成员" forState:UIControlStateNormal];
                [add setTitleColor:RealWhiteColor forState:UIControlStateNormal];
                [add.titleLabel setFont:REAL_MEDIUM_FONT(15)];
                add.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
                [[add rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    InviteView *view = [[InviteView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) GroupInfo:self.groupInfo];
                    [self.tabBarController.view addSubview:view];
                }];
                [self.view addSubview:add];
            }
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)switchBattryAction:(UISwitch *)sender
{
    [self.batteryArray[sender.tag-50] setValue:[NSString stringWithFormat:@"%d",sender.on] forKey:@"status"];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
    [param setValue:self.batteryArray[sender.tag-50][@"userId"] forKey:@"bnUserId"];
    [param setValue:self.batteryArray[sender.tag-50][@"status"] forKey:@"status"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPUT:@"/system/group/batterynotification"
    parameters:param
    success:^(NSDictionary *responseObject) {
        
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)switchSafeAction:(UISwitch *)sender
{
    [self.driveArray[sender.tag-100] setValue:[NSString stringWithFormat:@"%d",sender.on] forKey:@"status"];

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
    [param setValue:self.driveArray[sender.tag-100][@"userId"] forKey:@"bnUserId"];
    [param setValue:self.driveArray[sender.tag-100][@"status"] forKey:@"status"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPUT:@"/system/group/safedrivenotification"
    parameters:param
    success:^(NSDictionary *responseObject) {
        
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)ReloadNotification
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        switch (settings.authorizationStatus) {
            case UNAuthorizationStatusNotDetermined:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.notifyView.y = (self.notify.hidden?48:112);
                        [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.notifyView.frame)+32)];
                    });
                }
                break;
            case UNAuthorizationStatusDenied:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.notifyView.y = (self.notify.hidden?48:112);
                        [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.notifyView.frame)+32)];
                    });
                }
                break;
            case UNAuthorizationStatusAuthorized:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = YES;
                        self.notifyView.y = (self.notify.hidden?48:112);
                        [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.notifyView.frame)+32)];
                    });
                }
                break;
            case UNAuthorizationStatusProvisional:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.notifyView.y = (self.notify.hidden?48:112);
                        [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.notifyView.frame)+32)];
                    });
                }
                break;
            case UNAuthorizationStatusEphemeral:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.notifyView.y = (self.notify.hidden?48:112);
                        [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.notifyView.frame)+32)];
                    });
                }
                break;
        }
    }];
}

@end
 
